package com.lepu.app.fun.market;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.utils.IConstants;
import com.app.utils.LoginUtil;
import com.app.utils.MyStoreUtil;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.Reachability;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.widget.MyDialog;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.pasm.R;

/**
 * @ClassName WebViewActivity
 * @Description 网页链接加载界面  
 */
public class WebViewHstActivity extends BaseFragmentActivity implements
		AsyncRequest {

	private WebView webview;
	private WebView mCurrentView;// 复写的curretview
	private ProgressBar mProgressBar;
	private TextView tvTitle;
	private boolean isShow = false;// 是否显示退出框
	private int JUMPHSTPATH = -1;// -1 默认 0 购物车 1 订单中心

	private static final String REQUEST_DATA = "request_data";// token失效，请求
	private static final String REQUEST_ORDER = "request_order";// 兑换记录，我的订单
	//
	private boolean mIs_health_market = false;
	private boolean mIs_jifen_store = false;

	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {

		mNeedDefaultUmeng = false;
		mNeedSwipeBack = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.store_activity_hst_webview);

		init();

		Intent intent = getIntent();
		if (intent != null) {
			mIs_health_market = intent.getBooleanExtra("is_health_market",
					false);
			mIs_jifen_store = intent.getBooleanExtra("is_jifen_store", false);

			String url = intent.getStringExtra("url");
			webview.loadUrl(url);

			TextView tv_buy_record = (TextView) findViewById(R.id.tv_buy_record);
			tv_buy_record.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					MyStoreUtil.getInstance().requestSign(WebViewHstActivity.this);
				}
			});

			boolean flag = intent
					.getBooleanExtra("show_need_right_view", false);
			if (flag) {
				tv_buy_record.setVisibility(View.VISIBLE);
			} else {
				tv_buy_record.setVisibility(View.GONE);
			}
		}
	}

	@Override
	public void onResume() {
		super.onResume();

		if (mIs_health_market) {
			UmengHelper.onResume(this, UmengEvent.page_jiankangshangcheng);
		} else {
			UmengHelper.onResume(this, UmengEvent.page_wode_jifenduihuan);
		}

	}

	@Override
	public void onPause() {
		super.onPause();

		if (mIs_health_market) {
			UmengHelper.onPause(this, UmengEvent.page_jiankangshangcheng);
		} else {
			UmengHelper.onPause(this, UmengEvent.page_wode_jifenduihuan);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (webview != null) {
			try {
				LinearLayout linearLayout = (LinearLayout) findViewById(R.id.line_content);
				linearLayout.removeView(webview);
				webview.destroy();
			} catch (Exception e) {
				android.util.Log.d("错误 220 行", "webview Exception");
			}
		}
	}

	private void init() {
		mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
		mProgressBar.setMax(100);
		initWebView();
		// initSettings();
		Utils.initWebViewSettings(webview, false);

		ImageView back = (ImageView) findViewById(R.id.back);
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				leftClose();
			}
		});
	}

	private void initWebView() {
		tvTitle = (TextView) this.findViewById(R.id.tv_title);
		webview = (WebView) findViewById(R.id.webview);
		// webview.setWebViewClient(new WebViewClient() {});
		webview.setWebViewClient(new NewsWebViewClient());
		// webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		// webview.setInitialScale(100);
		// 触摸焦点起作用.如果不设置，则在点击网页文本输入框时，不能弹出软键盘及不响应其他的一些事件。
		webview.requestFocus();
		// 显示顶部加载条、设置title
		webview.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int progress) {
				mProgressBar.setProgress(progress);
				mProgressBar.setVisibility(View.VISIBLE);
				if (progress == 100) {
					mProgressBar.setVisibility(View.GONE);
				}
				super.onProgressChanged(view, progress);
			}

			@Override
			public void onReceivedTitle(WebView view, String title) {
				super.onReceivedTitle(view, title);
				tvTitle.setText(title);
			}
		});
		// 设置下载监听
		webview.setDownloadListener(new DownloadListener() {

			@Override
			public void onDownloadStart(String url, String userAgent,
					String contentDisposition, String mimetype,
					long contentLength) {
				Uri uri = Uri.parse(url);
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(intent);
			}
		});
		webview.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				// 禁止长按复制文本
				return true;
			}
		});
	}

	@SuppressWarnings("deprecation")
	@SuppressLint("SetJavaScriptEnabled")
	private void initSettings() {

		WebSettings webSettings;
		webSettings = webview.getSettings();
		webSettings.setJavaScriptEnabled(true); // 设置支持Javascript

		webSettings.setAppCacheMaxSize(524288);
		webSettings.setAppCacheEnabled(true);
		webSettings.setDefaultTextEncodingName("gb2312");
		webSettings.setLoadWithOverviewMode(true);
		DisplayMetrics outMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
		DecimalFormat format = new DecimalFormat("0.00");
		String formatResult = format.format((float) (outMetrics.widthPixels)
				/ (float) 320); // 320为html页面的宽度
		// 设置初始缩放大小 100% 屏幕宽度 / 网页设置的宽度
		webview.setInitialScale((int) (Float.valueOf(formatResult) * 100));// 39
	}

	public void finishPage() {
		webview.stopLoading();
		webview.clearHistory();
		finish(true);
	}

	private void dowithBack() {
		if (isShow) {
			isPayDialog();
			return;
		} else {

			if (mIs_health_market) {
				if (webview.canGoBack()) {
					webview.goBack();
				} else {
					finishPage();
				}
			} else {
				finishPage();
			}
		}
	}

	@Override
	public void onBackPressed() {

		if (mIs_jifen_store) {
			return;
		}
		dowithBack();
	}

	private void leftClose() {
		if (isShow) {
			isPayDialog();
		} else {
			finishPage();
		}
	}

	class NewsWebViewClient extends WebViewClient {

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);

			subStr(url);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if (!Reachability.checkNetwork(WebViewHstActivity.this)) {
				UIHelper.showToast(WebViewHstActivity.this,
						R.string.lib_check_network);
				return true;
			}
			LogUtilBase.LogD("webviewhstactivity", url);
			subStr(url);
			if (url.startsWith("goto::rebind?refresh=cart")) {
				JUMPHSTPATH = 0;
				refreshHtml(view);
			} else if (url.startsWith("goto::rebind?refresh=order_center")) {
				// 获取或者
				JUMPHSTPATH = 1;
				refreshHtml(view);
			} else if (url.startsWith("tel:")) {
				Utils.callPhone(WebViewHstActivity.this,
						url.substring(4, url.length()));
			} else if (url.startsWith("goto::rebind?refresh=stock")) { // 库存不足
				JUMPHSTPATH = 2;
				jumpToShip(view);
			}
			// else if (url.equals(IConstants.HSTURL)) {
			// WebViewHstActivity.this.finish();
			// }
			else if (url.startsWith("goto::goods")) {// 商品列表
				JUMPHSTPATH = 3;// 商品列表
				jumpToShip(view);
			} else if (url.startsWith("goto::cart")) { // 返回购物车
				JUMPHSTPATH = 4;// 返回购物车
				jumpToShip(view);
			} else if (url.startsWith("goto::url")) { // 跳转到新页面
				Intent intent = new Intent();
				intent.setAction("android.intent.action.VIEW");
				Uri content_url = Uri.parse(url.substring(9, url.length()));
				intent.setData(content_url);
				startActivity(intent);
			} else if (url.startsWith("goto:rebind?refresh=whole_check")) {
				view.loadUrl("");
			} else {
				view.loadUrl(url);
			}
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			mProgressBar.setVisibility(View.GONE);
		}

		@SuppressWarnings("deprecation")
		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			AlertDialog alertDialog = new AlertDialog.Builder(
					WebViewHstActivity.this).create();
			alertDialog.setTitle("ERROR");
			alertDialog.setMessage(description);
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					WebViewHstActivity.this.finish();
				}
			});
			alertDialog.show();
		}
	}

	private void subStr(String url) {
		if (!TextUtils.isEmpty(url) && url.length() > 8) {
			String var1 = url.substring(0, 7);
			if (var1.contains("https")) {
				isShow = true;
			} else {
				isShow = false;
			}
		}
	}

	/**
	 * accesstokne 失效进行
	 * 
	 * @param view
	 */
	private void refreshHtml(WebView view) {
		this.mCurrentView = view;

		String url = Setting.getMarketReBindUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			if (LoginUtil.checkIsLogin()) {
				LoginInfo loginInfo = MyApplication.getInstance()
						.getLoginInfo();
				params.put("UserID", loginInfo.UserID);
				params.put("LoginToken", loginInfo.LoginToken);
			} else {
				params.put("UserID", -1);
				params.put("LoginToken", "");
			}
			params.put("OS", "android");
			params.put("Osversion", AppManager.getDeviceModel(this));
			params.put("Resolution", "");
			params.put("DeviceSN", AppManager.getDeviceUniqueId(this));

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(url, map, null, this, REQUEST_DATA, true,
				false);
	}

	private void jumpToShip(WebView mCurrentView) {
		String permater = "ApplicationID=" + Setting.APPLICATIONID + "&UserID="
				+ LoginUtil.getUserId() + "&AccessToken="
				+ MyApplication.getInstance().getLoginInfo().HSTAccessToken
				+ "&DeviceID=2";
		if (mCurrentView != null) {
			switch (JUMPHSTPATH) {
			case 0:// 护生堂购物车
				mCurrentView.loadUrl(IConstants.HSTCart + permater);
				break;
			case 1: // 订单中心
				mCurrentView.loadUrl(IConstants.HSTORDERCENTER_MARKET
						+ MyStoreUtil.getInstance().mAppString);
				break;
			case 2: // 库存不足
				mCurrentView.loadUrl(IConstants.HSTINVENTORY);
				break;
			case 3: // 跳到订单列表
				mCurrentView.loadUrl(IConstants.HSTSHIP + permater);
				break;
			case 4: // 购物车
				mCurrentView.loadUrl(IConstants.HSTCart + permater);
				break;
			default:
				break;
			}
		}

	}

	/**
	 * 是否支付页面
	 */
	public void isPayDialog() {
		final MyDialog myDialog = new MyDialog(this);
		View view = View.inflate(this, R.layout.usercenter_ispay_dialog, null);
		myDialog.addView(view);
		myDialog.setPositiveButton(R.string.jixu_pay,
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						myDialog.dismiss();
					}
				});
		myDialog.setNegativeButton(R.string.isnotpay,
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						myDialog.dismiss();
						WebViewHstActivity.this.finish();
						// if (webview != null) {
						// JUMPHSTPATH = 3;
						// jumpToShip(webview);
						// }
					}
				});
		myDialog.create(null).show();
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		 if (object.equals(REQUEST_DATA)) {
			try {
				JSONObject jsonObject = new JSONObject((String) data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject dataObject = (JSONObject) obj1.get("DetailInfo");

				LoginInfo loginInfo = MyApplication.getInstance()
						.getLoginInfo();
				loginInfo.HSTAccessToken = dataObject
						.optString("HSTAccessToken");
				loginInfo.HSTAccessTokenExpireTime = dataObject
						.optString("HSTAccessTokenExpireTime");

				LoginInfo.saveLoginInfo(this, loginInfo);

				if (mCurrentView != null)
					jumpToShip(mCurrentView);
			} catch (Exception e) {

			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String data) {
		 if (object.equals(REQUEST_DATA)) {

		}
	}

}